package com.kewu.controller;

import com.kewu.bean.Fileup;
import com.kewu.dao.FileUploadMapper;
import com.kewu.utils.FileUtils;
import com.kewu.utils.MemoryUnitFormatting;
import com.kewu.utils.MybatisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
public class adminController {
    SqlSession session = MybatisUtils.getSession(true);
    FileUploadMapper mapper = session.getMapper(FileUploadMapper.class);

    @GetMapping("/admin")
    public String adminOne() {
        return "admin/adminlogin";
    }

    @GetMapping("/admin/login")
    public String adminLogin(Model model, String name, String password) {
        Map<String, Object> map = new HashMap();
        if ("admin".equals(name) && "admin".equals(password)) {
            model.addAttribute("msg", name);
            return "redirect:admin/listFile.html";
        } else {
            model.addAttribute("msg", "用户名错误");
            return "admin/adminlogin";
        }
    }

    /*去list页面*/
    @GetMapping("/admin/listFile.html")
    public String listPage(Model model) {
        SqlSession session = MybatisUtils.getSession(true);
        FileUploadMapper mapper = session.getMapper(FileUploadMapper.class);
        List<Fileup> all = mapper.findAll();
        if (all.size()==0)
            return "admin/listFile";
        for (Fileup f:all) {
        f.setFilePath(FileUtils.getFileName(f.getFilePath()));
        }
        model.addAttribute("fileup",all);
        String formatting = MemoryUnitFormatting.getFormatting(mapper.findsize());
        model.addAttribute("size",formatting);
        return "admin/listFile";
    }

    @GetMapping("/del")
    @ResponseBody
    public Map delid(Model model, @RequestParam("id") int id) {
        Map<String,String> map=new HashMap<>();
        Fileup byId = mapper.findById(id);
        if (FileUtils.delFile(new File(byId.getFilePath()))){
            int i = mapper.delectMd5(id);
            if (i>0){
                map.put("delid","删除成功");
            }else {
                map.put("delid","删除失败");
            }
        }else {
            map.put("delid","删除失败");
        }
        return map;
    }
}
